package com.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.book.bean.Book;
import com.book.biz.BookBiz;
import com.book.biz.impl.BookBizImpl;
import com.book.util.FileUtil;

@WebServlet("/FileupServlet")
@MultipartConfig
public class AddBookServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		String bname =request.getParameter("bname");
		String classify = request.getParameter("classify");
		String author = request.getParameter("author");
		String publisher = request.getParameter("publisher");
		String date_publish = request.getParameter("date_publish");
		double cost = Double.parseDouble(request.getParameter("cost"));
		
		
		//图片处理
		//获取上传文件的信息
		Part part  = request.getPart("bpicture");
		//获取上传的头文件
		String content = part.getHeader("content-disposition");
		//获取上传文件名
		String fileName=FileUtil.getaFileName(content);
		//获取上传文件的类型
		String fileType = FileUtil.getFileType(content);
		//保存到服务器的指定路径
		//获取服务器路径
		String url=request.getServletContext().getRealPath("/");
		System.out.println("保存成功");
		
		Book book = new Book();
		book.setBname(bname);
		book.setBpicture(fileName);
		book.setClassify(classify);
		book.setAuthor(author);
		book.setPublisher(publisher);
		book.setDate_publish(date_publish);
		book.setCost(cost);
		
		BookBiz bookBiz = new BookBizImpl();
		boolean flag = bookBiz.addBook(book);
		
		if(flag){
			out.print("<script>alert('OK');location='add_book.jsp';</script>");
		}else{
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		}
		
	}

}
